package cn.xkai.exercise.a;

/**
 * @description: 第一个错误的版本
 * 自己的思路：二分查找：越界的地方必然是出错的版本
 * 借鉴的思路：同理
 * @author: kaixiang
 * @date: 2022-07-12
 **/
public class Solution49 {
    public int firstBadVersion(int n) {
        int left = 1, right = n;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (isBadVersion(mid)) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
            if (left >= right) {
                if (isBadVersion(left)) {
                    return left;
                }
                if (isBadVersion(right)) {
                    return right;
                }
            }
        }
        return 1;
    }

    public int firstBadVersionRefer(int n) {
        int start = 1, end = n;
        while (start < end) {
            int mid = start + (end - start) / 2;
            if (!isBadVersion(mid)) {
                start = mid + 1;
            } else {
                end = mid;
            }
        }
        return start;
    }

    private boolean isBadVersion(int version) {
        return version == 3;
    }

    public static void main(String[] args) {
        int version = 5;
        Solution49 solution49 = new Solution49();
        System.out.println(solution49.firstBadVersion(version));
    }
}
